package cn.wd.service.impl;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.wd.common.EGoodsStatus;
import cn.wd.dao.GoodsBuyMapper;
import cn.wd.model.GoodsBuy;
import cn.wd.model.GoodsBuyKey;
import cn.wd.model.dto.GoodsBuyDTO;
import cn.wd.model.dto.GoodsDTO;
import cn.wd.service.GoodsBuyService;

@Service
public class GoodsBuyServiceImpl implements GoodsBuyService {
	@Autowired
	GoodsBuyMapper goodsBuyMapper;
	
	@Override
	public GoodsBuyDTO queryGoodsBuyDTO(String customerId, String goodsId,
			String shopBatch) {
		if(StringUtils.isEmpty(customerId)){
			return null;
		}
		if(StringUtils.isEmpty(goodsId)){
			return null;
		}
		GoodsBuyKey key = new GoodsBuyKey();
		key.setCustomerId(new Integer(customerId));
		key.setGoodsId(new Integer(goodsId));
		key.setShopBatch(shopBatch);
		GoodsBuy goodsBuy = goodsBuyMapper.selectByPrimaryKey(key );
		if(goodsBuy==null){
			return null;
		}
		GoodsBuyDTO goodsBuyDTO = null;
		try {
			goodsBuyDTO = new GoodsBuyDTO();
			BeanUtils.copyProperties(goodsBuyDTO, goodsBuy);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return null;
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			return null;
		}
		return goodsBuyDTO;
	}

	@Override
	public void createOrUpdate(GoodsDTO goodsDTO) throws Exception {
		GoodsBuyDTO goodsBuyDTO = queryGoodsBuyDTO(goodsDTO.getCustomerId(),goodsDTO.getGoodsId(),goodsDTO.getShopBatch());
		if(goodsBuyDTO!=null){
			//修改
			GoodsBuy goodsBuy = new GoodsBuy();
			goodsBuyDTO.setGoodsCount(goodsDTO.getGoodsCount());
			goodsBuyDTO.setGoodsStatus(goodsDTO.getGoodsStatus());
			try {
				BeanUtils.copyProperties(goodsBuy, goodsBuyDTO);
				goodsBuyMapper.updateByPrimaryKeySelective(goodsBuy);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
				throw new Exception(e);
			}
		}else{
			//新增
			GoodsBuy goodsBuy = new GoodsBuy();
			try {
				BeanUtils.copyProperties(goodsBuy, goodsDTO);
				goodsBuy.setGoodsStatus(EGoodsStatus.no_buy.getValue());
				goodsBuyMapper.insert(goodsBuy);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
				throw new Exception(e);
			}
		}
	}

}
